package com.epam.necklace.logic.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.epam.necklace.logic.exceptions.WrongFormatExeption;
import com.epam.necklace.model.stone.Stone;

public class GetTransparency {
	private static final Logger log = Logger.getLogger(GetTransparency.class);

	public void transparencySearch() throws IOException,
			ArrayIndexOutOfBoundsException, NumberFormatException {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					System.in));
			log.info("Please enter a range of transparency in the format start;end (Press 0 to return)");
			String range = reader.readLine();
			if (!range.isEmpty()) {
				if (range.equals("0")) {
					return;
				} else {
					String[] parts = range.split(";");
					String part1 = parts[0];
					String part2 = parts[1];
					double start = Double.parseDouble(part1);
					double end = Double.parseDouble(part2);
					if (start < 0 || start > 1 || end < 0 || end > 1
							|| end < start)
						throw new WrongFormatExeption();
					List<Stone> stones = new ArrayList<Stone>();
					for (Stone beads : Necklace.necklace) {
						if (beads.getTransparency() >= start
								&& beads.getTransparency() <= end) {
							stones.add(beads);
						}
					}
					StringBuilder out = new StringBuilder(
							"Stones from the entered range- ");
					for (Stone beads : stones) {
						out.append(beads).append(", ");
					}
					log.info(out);
				}
			} else {
				transparencySearch();
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			log.warn("Incorrect input, try again " + e);
			transparencySearch();
		} catch (WrongFormatExeption e) {
			transparencySearch();
		} catch (NumberFormatException e) {
			log.warn("Input the wrong number, try again " + e);
			transparencySearch();
		} catch (IOException e) {
			log.warn("Input problems, try again " + e);
			transparencySearch();
		}
	}
}
